//
//  WBMainViewController.swift
//  Weibo
//
//  Created by wade on 17/2/17.
//  Copyright © 2017年 wade. All rights reserved.
//

import UIKit

class WBMainViewController: UITabBarController {

    var timer : Timer?
    
    lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildControllers()
        setupComposeButton()
        setupNewFeatureView()
        
        setupTimer()
        
        
        delegate = self
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    deinit{
        
        timer?.invalidate()
        
        NotificationCenter.default.removeObserver(self)
    }
    
    func userLogin(n:Notification) {
        print("收到通知 \(n) ")
        
        let nav = UINavigationController(rootViewController: WBOAuthViewController())
        
        present(nav, animated: true, completion: nil)
        
    }
    

}

extension WBMainViewController{

    private var isNewVersion:Bool {
    
        return false
    
    }
    
    func setupNewFeatureView() {
        
        if !WBNetworkManager.shared.userLogon {
            return
        }
        
        let v = isNewVersion ? WBNewFeatureView() : WBWelcomeView.setupWBWelcomeView()
        
        v.frame = view.bounds
        
        view.addSubview(v)
        
    }

}


extension WBMainViewController : UITabBarControllerDelegate {

    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        let idx = childViewControllers.index(of: viewController)
        
        if selectedIndex == 0 && idx == selectedIndex
        {
            print("click indexview")
            
            let nav = childViewControllers[0] as! WBNavigationViewController
            
            let vc : WBHomeViewController = nav.childViewControllers[0] as! WBHomeViewController
            
            vc.tableview?.setContentOffset(CGPoint(x:0,y:-64), animated: true)
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: { 
                vc.loadData()
            })
            
            vc.tabBarItem.badgeValue = nil
            
        }
        
        
        
        
    
        return !viewController.isMember(of: UIViewController.self)
        
    }

}



extension WBMainViewController{

    func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 15.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    func updateTimer() {
        
        if !WBNetworkManager.shared.userLogon {
        
            return
        
        }
        
        
        WBNetworkManager.shared.unreadCount { (count) in
            
            print("have \(count) stauts unread")
            
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
        }
        
    }
    

}

extension WBMainViewController {

    func setupComposeButton(){
    
        tabBar.addSubview(composeButton)
        
        let count = CGFloat(childViewControllers.count)
        
        let w = tabBar.bounds.width / count
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        
    }
    
    func setupChildControllers(){
    
        let array:[[String:Any]] = [
            
            ["clsName":"WBHomeViewController","title":"首页","imageName":"home","vistorInfo":["imageName":"","message":"关注一些人,再回来看看有惊喜！"]],
            ["clsName":"WBMessageViewController","title":"消息","imageName":"message_center","vistorInfo":["imageName":"visitordiscover_image_message","message":"关注一些人,再回来看看有惊喜！"]],
            ["clsName":"xxx"],
            ["clsName":"WBDiscoverViewController","title":"发现","imageName":"discover","vistorInfo":["imageName":"visitordiscover_image_message","message":"关注一些人,再回来看看有惊喜！"]],
            ["clsName":"WBProfileViewController","title":"我的","imageName":"profile","vistorInfo":["imageName":"visitordiscover_image_profile","message":"关注一些人,再回来看看有惊喜！"]]
            
            ]
        
        var arrayV = [UIViewController]()
        
        for i in array {
            arrayV.append(controller(dict: i))
        }
        
        viewControllers = arrayV

    
    }
    
    private func controller (dict: [String:Any]) -> UIViewController {
    
        guard let clsName = dict["clsName"] as? String,
        let title = dict["title"] as? String,
        let imageName = dict["imageName"] as? String,
        let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
        let dic = dict["vistorInfo"] as? [String:String]
            
            else {
            
                return UIViewController()
        }
        
        let vc = cls.init()
        
        vc.title = title
        vc.vistorInfoDic = dic
        
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .selected)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 13)], for: .normal)
        
        
        let nav = WBNavigationViewController(rootViewController: vc)
        
        return nav
        
    }

}
